// pages/cart/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodList: [],
    totalMoney: 0,
    totalCount: 0,
    chooseAll: false
  },

  chooseAll: function () {
    var isChooseAll = !this.data.chooseAll;
    this.setData({
      chooseAll: isChooseAll
    })
    var goods = this.data.goodList;
    for (var i in goods) {
      goods[i].goodChecked = isChooseAll;
    }
    this.setData({
      goodList: goods
    })
    this.calculateCountAndMoney();
  },

  calculateCountAndMoney: function () {
    var goods = this.data.goodList;
    var totalMoney = 0;
    var totalCount = 0;
    for (var i in goods) {
      if (goods[i].goodChecked) {
        totalMoney += (goods[i].goodPrice * goods[i].goodCount);
        totalCount += 1;
      }
    }
    this.setData({
      totalMoney: totalMoney,
      totalCount: totalCount
    })
  },

  checkboxChange: function (e) {
    var i = e.currentTarget.dataset.index;
    var goods = this.data.goodList;
    goods[i].goodChecked = !goods[i].goodChecked;
    this.setData({
      goodList: goods
    })
    this.checkChooseAll();
    this.calculateCountAndMoney();
  },

  checkChooseAll: function () {
    var goods = this.data.goodList;
    var chooseAll = true;
    for (var i in goods) {
      if (goods[i].goodChecked) {
        continue;
      } else {
        chooseAll = false;
      }
    }
    this.setData({
      chooseAll: chooseAll
    })
  },

  getGoodListFromStorage: function () {
    var goods = new Array();
    var keys = wx.getStorageInfoSync().keys;
    for (var i in keys) {
      var key = keys[i];
      var obj = wx.getStorageSync(key);
      if (obj.goodId) {
        goods.push(obj);
      }
    }
    this.setData({
      goodList: goods
    })
    this.checkChooseAll();
  },

  createOrder:function(){
    wx.reLaunch({
      url:'/pages/order/index'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '购物车',
      success: function (res) {
        // success
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getGoodListFromStorage();
    this.calculateCountAndMoney();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})